package loaders
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import utils.Disposeable;

	[Event(name="complete",type="flash.events.Event")]
	[Event(name="change",type="flash.events.Event")]
	[Event(name="loadError",type="com.pickgliss.events.LoaderEvent")]
	[Event(name="progress",type="com.pickgliss.events.LoaderEvent")]
	public class LoaderQueue extends EventDispatcher implements Disposeable
	{
		
		public function LoaderQueue()
		{
			_loaders = new Vector.<ILoader>();
		}

		private var _loaders:Vector.<ILoader>;
		
		public function addLoader(loader:ILoader):void
		{
			_loaders.push(loader);
		}
		
		public function dispose():void
		{
			removeEvent();
			_loaders = null;
		}
		
		public function removeEvent():void
		{
			for(var i:int = 0;i<_loaders.length;i++)
			{
				_loaders[i].removeEventListener(LoaderEvent.COMPLETE,__loadNext);
			}
		}
		
		public function isAllComplete():Boolean
		{
			for(var i:int = 0;i<_loaders.length;i++)
			{
				if(!_loaders[i].isComplete)return false;
			}
			return true;
		}
		
		public function isLoading():Boolean
		{
			for(var i:int = 0;i<_loaders.length;i++)
			{
				if(_loaders[i].isLoading)return true;
			}
			return false;
		}
		
		public function get completeCount():int
		{
			var result:int = 0;
			for(var i:int = 0;i<_loaders.length;i++)
			{
				if(_loaders[i].isComplete)result++;
			}
			return result
		}
		
		public function get length():int
		{
			return _loaders.length;
		}
		
		public function get loaders():Vector.<ILoader>
		{
			return _loaders;
		}
		
		public function start():void
		{
			tryLoadNext();
		}
		
		private function __loadNext(event:LoaderEvent):void
		{
			event.loader.removeEventListener(LoaderEvent.COMPLETE,__loadNext);
			event.loader.removeEventListener(LoaderEvent.PROGRESS,__loadProgress);
			event.loader.removeEventListener(LoaderEvent.LOAD_ERROR,__loadError);
			dispatchEvent(new Event(Event.CHANGE));
			tryLoadNext();
		}
		
		private function tryLoadNext():void
		{
			//TODO 不知道是什么原因 _loaders为null 以后再查查是什么原因
			if(_loaders == null)return;
			var loaderCount:int = _loaders.length;
			for(var i:int = 0;i < loaderCount;i++)
			{
				if(!_loaders[i].isComplete)
				{
					_loaders[i].addEventListener(LoaderEvent.COMPLETE,__loadNext);
					_loaders[i].addEventListener(LoaderEvent.PROGRESS,__loadProgress);
					_loaders[i].addEventListener(LoaderEvent.LOAD_ERROR,__loadError);
					LoaderManager.Instance.startLoad(_loaders[i]);
					return;
				}
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function __loadError(event:LoaderEvent):void
		{
			dispatchEvent(event);
		}
		
		private function __loadProgress(event:LoaderEvent):void
		{
			dispatchEvent(event);
		}
	}
}